package com.seoultour.joel.hadoop;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Closeable;
import java.io.IOException;

public class HDFSBeanFactory implements Closeable {
	private String fsDefaultName;

	private FileSystem fileSystem = null;

	public FileSystem getFileSystem() throws IOException {
		if (fileSystem == null) {
			Configuration conf = new Configuration(true);
			conf.set("fs.default.name", fsDefaultName);
			fileSystem = FileSystem.get(conf);
		}
		return fileSystem;
	}

	public void close() throws IOException {
		if (fileSystem != null)
			fileSystem.close();
	}

	public void setFsDefaultName(String fsDefaultName) {
		fsDefaultName = this.fsDefaultName;
	}

	public static abstract class Support {
		@Autowired
		private HDFSBeanFactory factory;

		protected FileSystem getFileSystem() {
			try {
				return factory.getFileSystem();
			} catch(IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
